package com.nba.common.utils;

import java.io.UnsupportedEncodingException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.codec.digest.DigestUtils;

public class CommonUtils {
	/**
	 * 解码
	 * @param src
	 * @return
	 */
	public static String  unescape (String src){
		StringBuffer tmp = new StringBuffer();
		if(src!=null){
			tmp.ensureCapacity(src.length());
			int  lastPos=0,pos=0;
			char ch;
			while (lastPos<src.length()){
				pos = src.indexOf("%",lastPos);
				if (pos == lastPos){
					if (src.charAt(pos+1)=='u'){
						ch = (char)Integer.parseInt(src.substring(pos+2,pos+6),16);
						tmp.append(ch);
						lastPos = pos+6;
					}else{
						ch = (char)Integer.parseInt(src.substring(pos+1,pos+3),16);
						tmp.append(ch);
						lastPos = pos+3;
					}
				}else{
					if (pos == -1){
						tmp.append(src.substring(lastPos));
						lastPos=src.length();
					}else{
						tmp.append(src.substring(lastPos,pos));
						lastPos=pos;
					}
				}
			}
		}
		return tmp.toString();
	}
	/**
     * 解密
     * @param content
     * @param password
     * @return
     */
    public static String decrypt(String content, String password) {
        try {
            if (content.length() < 1)
                return null;
            byte[] result = new byte[content.length() / 2];
            for (int i = 0; i < content.length() / 2; i++) {
                int high = Integer.parseInt(content.substring(i * 2, i * 2 + 1), 16);
                int low = Integer.parseInt(content.substring(i * 2 + 1, i * 2 + 2), 16);
                result[i] = (byte) (high * 16 + low);
            }
            KeyGenerator kgen = KeyGenerator.getInstance("AES");
            SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG");
            secureRandom.setSeed(password.getBytes()); 
            kgen.init(128, secureRandom);
            SecretKey secretKey = kgen.generateKey();
            byte[] enCodeFormat = secretKey.getEncoded();
            SecretKeySpec key = new SecretKeySpec(enCodeFormat, "AES");
            Cipher cipher = Cipher.getInstance("AES");// 创建密码器
            cipher.init(Cipher.DECRYPT_MODE, key);// 初始化
            return new String(cipher.doFinal(result),"utf-8");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
	/**
     * 将参数连接后取得MD5的签名
     * @param param
     * @return
     */
    public static String getSignByMD5(Map<String,String> param,String securityKey){
        List<String> keyList=new ArrayList<String>();
        keyList.addAll(param.keySet());
        Collections.sort(keyList, new Comparator<String>(){
            @Override
            public int compare(String o1, String o2) {
                return o1.compareToIgnoreCase(o2);
            }
        });
        StringBuffer str=new StringBuffer();
        for(String key:keyList){
            str.append(param.get(key));
        }
        str.append(securityKey);
        return DigestUtils.md5Hex(str.toString()).toLowerCase();
    }
    /**
     * 计算签名
     * @param requestString
     * @param key
     * @return
     * @throws NoSuchAlgorithmException
     * @throws UnsupportedEncodingException
     */
    private String ComputeSignature(String requestString, String key)
            throws NoSuchAlgorithmException, UnsupportedEncodingException {
        java.security.MessageDigest md5 = java.security.MessageDigest
                .getInstance("MD5");
        char[] hex = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a',
                'b', 'c', 'd', 'e', 'f' };

        byte[] source = (requestString + key).toLowerCase().getBytes("UTF-8");
        md5.update(source);
        byte[] data = md5.digest();

        char[] result = new char[data.length * 2];
        for (int i = 0, j = 0; i < data.length; i++, j += 2) {
            result[j] = hex[data[i] >> 4 & 0x0f];
            result[j + 1] = hex[data[i] & 0x0f];
        }

        return new String(result);
    }
	/**
	  * 把中文字符转成unicode编码如%u6859
	  * @param s 要转的中文
	  * @return
	  */
	 public static String ChineseToUnicode(String   s){   
		  StringBuffer   bu   =   new   StringBuffer(s);   
		  String   unicode   =   "";   
		  for(int   i   =   0;   i   <   bu.length();   i++)   {   
			  //String   tmp   =   Integer.toHexString((int)bu.charAt(i));   
			  int   tmp   =   bu.charAt(i);//Integer.toHexString((int)bu.charAt(i)); 
			  if((tmp   >>   8)>0){//判断是否为中文
				  unicode   =   unicode   +   "%u"   +Integer.toHexString(tmp);//unicode   =   unicode   +   "$$u"   +Integer.toHexString(tmp);//因为dwr不支持%所有换成$$
			  }else{
				  unicode   =   unicode   +bu.charAt(i);
			  }
			  //tmp   =   (tmp   >>   8)   |   ((tmp   <<   8)   &   0xff00) ;
			  // unicode   =   unicode   +   "%u"   +   tmp;   
		  }   
		  return   unicode;   
	 }
	
	
	/**
	 * 生成固定长度的字符串
	 * @param str: 原数值
	 * @param len: 总长度
	 * @param supplement: 补充字符 如:"0"
	 * @param orientation: 补充的方向(左边:0,右边1)
	 * @return String 如:"000000001"
	 */
	public static String getConstancyStr(String str, int len, char supplement, int orientation) {
		if (str.length()>=len) return str;
		StringBuffer returnStr = new StringBuffer();
		StringBuffer tmp = new StringBuffer("");
		for (int i=str.length(); i<len; i++) {
			tmp.append(supplement);
		}
		if (orientation==0) {
			returnStr.append(tmp.toString());
			returnStr.append(str);
		} else if (orientation==1) {
			returnStr.append(str); 
			returnStr.append(tmp.toString());
		} 
		return returnStr.toString();
	}
	
	public static String getFullContextPath(HttpServletRequest request){
	    String path = "";
	    try{
	        path = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+request.getContextPath();
	    }catch(Exception e){
	        e.printStackTrace();
	    }
	    return path;
	}
}
